package com.vsked.io;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Method;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * FileOperate
 * @author vsked
 *
 */
public class FileOperate {
	private static String[] af=null;
	public static String imageExt="bmp,BMP,JPG,jpg,JPEG,jpeg,gif,GIF,";
	public static String voiceExt="wav,WAV,MP3,mp3,amr,AMR,";
	public static String excelExt="XLS,xls,";
	/**
	 * file save path
	 */
	public static String excelSavePath = "./export.xls";
	
	public static String getExcelSavePath() {
		return excelSavePath;
	}

	public static void setExcelSavePath(String excelSavePath) {
		FileOperate.excelSavePath = excelSavePath;
	}

	/**
	 * sheetCount
	 */
	private static int sheetIndexTest = 1;
	/**
	 * maxRow
	 */
	private int rowIndexTest = 4;
	/**
	 * maxColumn
	 */
	private int colIndexTest = 6;

	
	
	/**
	 * read file
	 * @param fname
	 * @return
	 */
	public static String readFile(String fname) {
		String content = "";
		try {
			FileReader fr = new FileReader(new File(fname));
			BufferedReader br = new BufferedReader(fr);
			while (br.ready()) {
				String s = br.readLine();
				if("".equals(content))
				{
				  content=s;
				}else{
				  content += s + "#";
				}
			}
			br.close();
			fr.close();
		} catch (Exception ex) {
		}

		return content;
	}
	
    /**
     * readFile by Encoding
     * @param fname 文件路径
     * @param enCoding 编码方式
     * @return
     */
	public static String readFile(String fname,String enCoding) {
		String content = "";
		try {
			BufferedReader br = new BufferedReader(new BufferedReader(new InputStreamReader(new FileInputStream(new File(fname)),enCoding.trim())));
			while (br.ready()) {
				String s = br.readLine();
				if("".equals(content))
				{
				  content=s;
				}else{
				  content += s + "#";
				}
			}
			br.close();
		} catch (Exception ex) {
		}

		return content;
	}//end method
	
	public static String[] readAllFilesinDirectory(String strv) {
		File f = new File(strv);
		if(f.list()!=null){
		String fs[] = f.list();	
		af=new String[fs.length];
			for (int i = 0; i < fs.length; i++) {				
				File fv = new File(fs[i]);
				if (fv.canWrite()) {
					break;
				} else {
					try {
						//System.out.println(f.getCanonicalPath() + fs[i]);
						af[i]=fs[i];
//						VskVmethodBody.readAllDirectory(f.getCanonicalPath() + fs[i]);						
					} catch (Exception e) {						
						e.printStackTrace();
					}
				}
			}
		}
		return af;
	}
	/**
	 * write excel to file
	 */
	public static void writeExcel(Object[][] inArray) {
		try {
			if(inArray==null){
				inArray=new Object[0][0];
			}
			// create new Excel workbook 　
			HSSFWorkbook workbook = new HSSFWorkbook();
			for (int sheetIndex = 0; sheetIndex < sheetIndexTest; sheetIndex++) {
				// create new sheet in workbook
				HSSFSheet sheet = workbook.createSheet("sheet" + sheetIndex);
				// HSSFSheet sheet = workbook.createSheet();
				for (int rowIndex = 0; rowIndex < inArray.length; rowIndex++) {
					// create row in sheet
					HSSFRow row = sheet.createRow(rowIndex);
					for (int colIndex = 0; colIndex < inArray[0].length; colIndex++) {
						// create column in row
						HSSFCell cell = row.createCell(colIndex);
						// set the cell data type
						cell.setCellType(HSSFCell.CELL_TYPE_STRING);
						// set the cell data
						cell.setCellValue(inArray[rowIndex][colIndex].toString());
					}// end for colIndex
				}// end for rowIndex
			}// end for sheetIndex
			// new FileOutputStream
			FileOutputStream fOut = new FileOutputStream(excelSavePath);
			// save the excel workbook
			workbook.write(fOut);
			fOut.flush();
			// finish operate close file
			fOut.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}// end method writeExcel

    /**   
     * delete file or Directory
     * @param   fileName      
     * @return delete success return true else false
     */   
    public static boolean delete(String fileName){    
        File file = new File(fileName);    
        if(!file.exists()){    
            System.out.println("delete file fail："+fileName+" file not found ");    
            return false;    
        }else{    
            if(file.isFile()){    
                    
                return deleteFile(fileName);    
            }else{    
                return deleteDirectory(fileName);    
            }    
        }    
    }    
        
    /**   
     * delete a file  
     * @param   fileName    
     * @return delete success return true else false
     */   
    public static boolean deleteFile(String fileName){    
        File file = new File(fileName);    
        if(file.isFile() && file.exists()){    
            file.delete();    
            System.out.println("delete a file "+fileName+" success！");    
            return true;    
        }else{    
            System.out.println("delete a file "+fileName+" fail！");    
            return false;    
        }    
    }    
        
    /**   
     * delete file or file in Directory or Folder
     * @param   dir file or Directory  
     * @return  delete success return true,else false   
     */   
    public static boolean deleteDirectory(String dir){    
        if(!dir.endsWith(File.separator)){    
            dir = dir+File.separator;    
        }    
        File dirFile = new File(dir);    
        if(!dirFile.exists() || !dirFile.isDirectory()){    
            System.out.println("delete directory fail"+dir+"The directory not found！");    
            return false;    
        }    
        boolean flag = true;    
        //删除文件夹下的所有文件(包括子目录)   
        //delete all file or directory in folder
        File[] files = dirFile.listFiles();    
        for(int i=0;i<files.length;i++){    
            //delete subFile
            if(files[i].isFile()){    
                flag = deleteFile(files[i].getAbsolutePath());    
                if(!flag){    
                    break;    
                }    
            }    
            //delete subDirectory
            else{    
                flag = deleteDirectory(files[i].getAbsolutePath());    
                if(!flag){    
                    break;    
                }    
            }    
        }    
            
        if(!flag){    
            System.out.println("delete directory fail");    
            return false;    
        }    
            
        //delete current directory
        if(dirFile.delete()){    
            System.out.println("delete directory"+dir+"success！");    
            return true;    
        }else{    
            System.out.println("delete directory"+dir+"fail！");    
            return false;    
        }    
    }    
    
	public static String getDBConfig(String fname){		
		return FileOperate.readFile(fname);
		
	}
	
	/**
	 * read excel file
	 */
	public static Object[][] readExcel(String inFile) {
		Object[][] tempArray=null;
		try {
			// read the workbook in file
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inFile));
			// get the sheet in workbook
			// HSSFSheet sheet = workbook.getSheet("Sheet0");
			int sheetIndexTest=workbook.getNumberOfSheets();
			
			for (int sheetIndex = 0; sheetIndex < sheetIndexTest; sheetIndex++) {
				// you can use getSheetAt(int index) get the sheet in workbook
				HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
				int rowIndexTest=sheet.getPhysicalNumberOfRows();
				for (int rowIndex = 0; rowIndex < rowIndexTest; rowIndex++) {
					HSSFRow row = sheet.getRow(rowIndex);
					int colIndexTest=row.getLastCellNum();
					for (int colIndex = 0; colIndex < colIndexTest; colIndex++) {
						HSSFCell cell = row.getCell(colIndex);
						if(tempArray==null){
							tempArray=new String[rowIndexTest][colIndexTest];
						}
						//System.out.print("["+rowIndex + ":" + colIndex + "||"	+ cell.getStringCellValue()+"]");
						//System.out.println(rowIndex+"|"+colIndex+"|"+(cell.getCellType()==cell.CELL_TYPE_NUMERIC?cell.getNumericCellValue():cell.getStringCellValue()));
						tempArray[rowIndex][colIndex]=(String)(cell.getCellType()==cell.CELL_TYPE_NUMERIC?(String.valueOf(cell.getNumericCellValue()).replace(".", "").replace("E10", "")):cell.getStringCellValue());
					}// end for colIndex
					//System.out.println();
				}// end for rowIndex
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tempArray;

	}// end method readExcel
	
	/** 
     * copy file
     * @param oldPath String source file：c:/fqf.txt 
     * @param newPath String now file：f:/fqf.txt 
     * @return boolean 
     */ 
   public static void copyFile(String oldPath, String newPath) { 
       try { 
           int bytesum = 0; 
           int byteread = 0; 
           File oldfile = new File(oldPath); 
           if (oldfile.exists()) { //exists file
               InputStream inStream = new FileInputStream(oldPath); //read sourcefile
               FileOutputStream fs = new FileOutputStream(newPath); 
               byte[] buffer = new byte[1444]; 
               int length; 
               while ( (byteread = inStream.read(buffer)) != -1) { 
                   bytesum += byteread;
                   System.out.println(bytesum); 
                   fs.write(buffer, 0, byteread); 
               } 
               inStream.close(); 
           } 
       } 
       catch (Exception e) { 
           System.out.println("copy file error"); 
           e.printStackTrace(); 

       } 

   }//end copy file	
   
   /** 
    * new folder
    * @param folderPath String like c:/fqf 
    * @return boolean 
    */ 
  public static void newFolder(String folderPath) { 
      try { 
          String filePath = folderPath; 
          filePath = filePath.toString(); 
          java.io.File myFilePath = new java.io.File(filePath); 
          if (!myFilePath.exists()) { 
              myFilePath.mkdir(); 
          } 
      } 
      catch (Exception e) { 
          System.out.println("new Folder error"); 
          e.printStackTrace(); 
      } 
  }//end newFolder 

  /** 
    * new file
    * @param filePathAndName String filePath 如c:/fqf.txt 
    * @param fileContent String file Content
    * @return boolean 
    */ 
  public static void newFile(String filePathAndName, String fileContent) { 

      try { 
          String filePath = filePathAndName; 
          filePath = filePath.toString(); 
          File myFilePath = new File(filePath); 
          if (!myFilePath.exists()) { 
              myFilePath.createNewFile(); 
          } 
          FileWriter resultFile = new FileWriter(myFilePath); 
          PrintWriter myFile = new PrintWriter(resultFile); 
          String strContent = fileContent; 
          myFile.println(strContent); 
          resultFile.close(); 

      } 
      catch (Exception e) { 
          System.out.println("new file error"); 
          e.printStackTrace(); 

      } 

  }//end newFile 
  
  /**
   * new file
   * @param filePathAndName file save path
   * @param fileContent 
   * @param encoding 
   */
  public static void newFile(String filePathAndName, String fileContent,String encoding) { 

      try { 
          String filePath = filePathAndName; 
          filePath = filePath.toString(); 
          File myFilePath = new File(filePath); 
          if (!myFilePath.exists()) { 
              myFilePath.createNewFile(); 
          } 
          Writer resultFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(myFilePath), encoding));
          PrintWriter myFile = new PrintWriter(resultFile); 
          String strContent = fileContent; 
          myFile.println(strContent); 
          resultFile.close(); 

      } 
      catch (Exception e) { 
          System.out.println("new file error"); 
          e.printStackTrace(); 
      } 

  }//end newFile
  
 /**
  * file encoding
  * @param oldPath 
  * @param newPath 
  * @param oldEncoding 
  * @param newEncoding 
  */
  public static void changeEncoding(String oldPath, String newPath,
			String oldEncoding,String newEncoding) {
		try {
			File file = new File(oldPath); // get old file
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),oldEncoding));
			File file2 = new File(newPath);// change encoding path
			file2.createNewFile();
			FileWriter fw = new FileWriter(file2);
			BufferedWriter bw = new BufferedWriter(fw);
			String str;
			while ((str = br.readLine()) != null) {
				bw.write(new String(str.getBytes(), newEncoding));
			}
			br.close();
			fr.close();
			bw.close();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

  }//end changeEncoding
	
  /**
	 * 
	 * @param inFilePath
	 * @param outFilePath
	 * @param inWidth
	 * @param inHeight
	 */
	public static void changePictureSize(String inFilePath,String outFilePath,int inWidth,int inHeight){
		File src = new File(inFilePath) ;
      try {
          Image image = ImageIO.read(src) ;
          int width = inWidth ;
          int height = inHeight ;
          BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB) ;
          bufferedImage.getGraphics().drawImage(image, 0, 0, width, height,null) ;
          FileOutputStream fos = new FileOutputStream(outFilePath) ;
          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos) ;
          encoder.encode(bufferedImage) ;
          fos.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
		
	}
	
	public static void saveFile(String str)
	{
		JFileChooser jfch = new JFileChooser();
		int x = jfch.showSaveDialog(null);
		if(x==0)
		{
			String fpath = jfch.getSelectedFile().getAbsolutePath();			
			try {
				File f = new File(fpath);
				FileWriter fw = new FileWriter(f,true);
				fw.write(str);
				fw.close();				
		    }
		    catch (Exception e) {
		    	e.printStackTrace();
		    }			
		}//end if
	}//end save file
	
	 public void rename(String inOldName,String inNewName){   
		 File f=new File(inOldName);
		 f.renameTo(new File(inNewName));
	 }
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Double d=new Double("3.33");
		System.out.println(d.toString());
		FileOperate.excelSavePath="c:/ts.xls";
		Object[][] ts=FileOperate.readExcel(FileOperate.excelSavePath);
		for(int i=0;i<ts.length;i++){
			for(int k=0;k<ts[0].length;k++)
			System.out.println(ts[i][k]);
		}
		
	}//end main method

}
